/**
 * egahi JS Lib
 * 
 * Copyright 2010, egahi
 * 
 * http://www.egahi.com/
 */
var egahi = {
	
	debugMode : false, // set to false when online
	ajaxLog : new Array(),


	showMessage : function(message){
		$("#message").text(message);
		$("#message").fadeIn("normal");
		setTimeout(egahi.hideMessage,10000);
	},
	
	hideMessage : function(){
		$("#message").fadeOut("normal");
	},

	
	
	/**
	 * gets called when a like button clicked
	 * @param event e
	 */
	likeAd : function(e) {
		var id = $(e.currentTarget).parent().attr("data-egahi-id");
		egahi.ajax({
			url : BASEURL + "/ads/like/"+id+"/",
			method : "get",
			callback : function(response) {
				try{
					resObj = eval(response); // we expect server response to be a json object, this throws exception otherwise
					if(resObj.success == true){
						// setting new tooltip for buttons
						newTitle = "مجموع امتیازات این آگهی :"+resObj.data+"<br />امتیاز داده شده توسط شما : (۱+)";
						$("button", $(e.currentTarget).parent()).each(function () {
							$(this).unbind("mouseenter"); // unbinding last handlers for hover event
							$(this).simpleTooltip({title:newTitle});
						});
						// immediately set tooltip text
						$("#v-tooltip").html(newTitle);
					}
					egahi.showMessage(resObj.message);
				}catch(e){
					egahi.showMessage("Oops, server error 100");
				}
			}
		});
	},
	
	
	
	
	/**
	 * gets called when a dislike button clicked
	 * @param event e
	 */
	disLikeAd : function(e){
		var id = $(e.currentTarget).parent().attr("data-egahi-id");
		egahi.ajax({
			url : BASEURL + "/ads/dislike/"+id+"/",
			method : "get",
			callback : function(response) {
				try{
					resObj = eval(response); // we expect server response to be a json object, this throws exception otherwise
					if(resObj.success == true){
						// setting new tooltip for buttons
						newTitle = "مجموع امتیازات این آگهی :"+resObj.data+"<br />امتیاز داده شده توسط شما : (۱-)";
						$("button", $(e.currentTarget).parent()).each(function () {
							$(this).unbind("mouseenter"); // unbinding last handlers for hover event
							$(this).simpleTooltip({title:newTitle});
						});
						// immediately set tooltip text
						$("#v-tooltip").html(newTitle);
					}
					egahi.showMessage(resObj.message);
				}catch(e){
					egahi.showMessage("Oops, server error 100");
				}
			}
		});
	},
	
	
	
	/**
	 * Fetch a specific page data, from server
	 * @param event e
	 */
	getPage : function(e){
		
		// preventing actual browsing the url 
		e.preventDefault();
		
		var href = $(e.currentTarget).attr("href");
		
		egahi.ajax({
			url : BASEURL + href,
			method : "post",
			callback : function(response) { 
				try{
					resObj = eval(response);
					if(resObj.success == true){
						
						// see if we have the same new items number with last page
						if(resObj.data.length != $(".explore > .item ").length){
							
							// try to get an item html
							itemHTML = $($(".explore > .item ")[0]).wrapInner($("<div></div>").addClass("item")).html();
							
							$(".explore .item").remove();
							$(".explore .clear").remove();
							
							// adding place holders for new items 
							var i = 1;
							while(resObj.data.length > $(".explore > .item ").length){
								if(i++ % 3 == 0){
									$(".explore").html($(".explore").html() + itemHTML + "<br class='clear'/>");
								}else{
									$(".explore").html($(".explore").html() + itemHTML);
								}
							}
						}
						
						$.each(resObj.data,function(i,item){
							$.each($(".explore > .item "),function(j,element){
								if(i == j){
									
									// update each item with new data
									$(element).children("div").children(".ad-title").html(item.title);
									$(element).children("div").children(".ad-title").attr("href","/ads/view/" + item.id + "/");
									$(element).children("div").children(".dislikes").html(item.dislikes);
									$(element).children("div").children(".likes").html(item.likes);
									$(element).children(".ad-desc").html(item.description);
									$(element).children(".ad-advertiozer").html(item.advertizerTitle);
								}
							});
						});
						
						// links
						egahi.setPagingLinks(resObj.paging);
						
					}else{
						egahi.showMessage(resObj.message);
					}
					
				}catch(e){ // exception
					egahi.showMessage("Oops, server error 100");
				}
			}
		});
	},
	
	
	
	
	/**
	 * Generate and set links for paging
	 * @param object resObjPaging
	 */
	setPagingLinks : function(resObjPaging){
		
		// Next page button link
		if(resObjPaging.has_next){
			var newNextButtonHref = "";
			var nextPageNumber = parseInt(resObjPaging.next);
			
			// new link
			newNextButtonHref = resObjPaging.base_url + "/page/" + nextPageNumber + "/";
			
			// check to see if next button was disable
			if($(".paginator .next a").length > 0){
				$(".paginator .next a").attr("href",newNextButtonHref);
			}else{
				$(".paginator .next-na").wrapInner($("<a></a>").attr("href",newNextButtonHref).attr("title",""));
				$(".paginator .next-na").removeClass("next-na").addClass("next");
			}
		}else{ // no next page, disable button
			$(".paginator .next").html($(".paginator .next a").html());
			$(".paginator .next").removeClass("next").addClass("next-na");
		}
		
		// Previous page button link
		if(resObjPaging.has_previous){
			var newPrevButtonHref = "";
			var prevPageNumber = parseInt(resObjPaging.previous);
			
			// new link
			newPrevButtonHref = resObjPaging.base_url + "/page/" + prevPageNumber + "/";
			
			// check to see if prev button was disable
			if($(".paginator .prev a").length > 0){
				$(".paginator .prev a").attr("href",newPrevButtonHref);
			}else{
				$(".paginator .prev-na").wrapInner($("<a></a>").attr("href",newPrevButtonHref).attr("title",""));
				$(".paginator .prev-na").removeClass("prev-na").addClass("prev");
			}
		}else{ // no prev page, disable button
			$(".paginator .prev").html($(".paginator .prev a").html());
			$(".paginator .prev").removeClass("prev").addClass("prev-na");
		}
		
		// Current page button link
		currentPageButtonHref =  resObjPaging.base_url + "/page/" + $(".paginator .curr").html() + "/";
		$(".paginator .curr").wrapInner($("<a></a>").attr("href",currentPageButtonHref).attr("title",""));
		$(".paginator .curr").removeClass("curr").addClass("page");
		
		// finding new cuurent page
		$.each($(".paginator span"),function(i,element){
			if($(element).children("a").html() == resObjPaging.page){
				$(element).removeClass("page").addClass("curr");
				$(element).html(resObjPaging.page);
			}
		});
		
		// unbind handler from last buttons and set it for new ones
		$(".next a, .prev a, .page a").unbind("click");
		$(".next a, .prev a, .page a").bind("click",egahi.getPage);
		
	},

	
	
	
	
	
	/**
	 * Every ajax calls to server should use this function
	 * @param object args
	 */
	ajax : function(args) {
		$.ajax({
			timeout : 12000,
			async : true,
			type : args.method,
			cache : false,
			data : args.params,
			complete : function(XMLHttpRequest, type) {
				if (egahi.debugMode) {
					var log = { // log the "request and response" when in debug mode
						method : args.method,
						url : args.url,
						params : args.params,
						responseType : type,
						XMLHttpRequest : XMLHttpRequest
					};
					egahi.ajaxLog.push(log);
				}
			},
			url : args.url,
			error : egahi.ajaxError,
			success : args.callback
		});
	},

	ajaxError : function(XMLHttpRequest, textStatus, errorThrown) {
		egahi.showMessage(" Oops, server error 200");
	}

};


// when dom is ready
$(function() {
	// show page
	$("#wrapper").fadeIn("slow");
	
	/** begin events handlers **/
	
		// loading
		$("#loading").ajaxStart(function(){ 
			$(this).fadeIn("slow");
		});
		$("#loading").ajaxStop(function(){
			$(this).fadeOut("normal");
		});
		
		
		// like and dislike
		$("#like").bind("click", egahi.likeAd);
		$("#dislike").bind("click", egahi.disLikeAd);
		$("#like, #dislike").simpleTooltip();
		
		// paging
		if($(".explore .item").length > 0){
			$(".next a, .prev a, .page a").bind("click",egahi.getPage);
		}
		
		// faq
		$("ol.faq li div").click(function(){
			$(this).next("ul").toggle("slow");
			$(this).next("ul").children("li").children("p").slideUp("fast");
		});
		$(".question").click(function(){
			var currentAnswer = $(this).next(".answer");
			$.each($("p.answer"),function(){
				if($(this).html() != currentAnswer.html())
					$(this).slideUp("normal");
			});
			currentAnswer.slideToggle("slow");
		});

	/** end events handlers **/
});